from langchain.embeddings import CacheBackedEmbeddings
from langchain.storage import LocalFileStore
from langchain_community.embeddings import DashScopeEmbeddings
from langchain_community.vectorstores import FAISS


class Dbutils:
    def __init__(self):
         # 将创建缓存嵌入器对象的步骤移到__init__方法中
         self.embeddings=DashScopeEmbeddings()
         self.store = LocalFileStore("./cache/")
         self.cached_embedder = (
             CacheBackedEmbeddings.from_bytes_store(self.embeddings, self.store, namespace=self.embeddings.model))
# 添加数据
    def add_data(self, chunks,key):
           db=FAISS.from_documents(chunks, self.cached_embedder)
           # 以索引的方式保存
           db.save_local(key)
# 查询数据
    def query_data(self,key,question,count):
           db=FAISS.load_local(key,self.cached_embedder,allow_dangerous_deserialization=True)
           return db.similarity_search(question,k=count)
